import { createSlice } from '@reduxjs/toolkit';
import { incrementAge } from './person';

function fetchCountApi(amount = 1) {
  return new Promise((resolve) =>
    setTimeout(() => resolve({ data: amount }), 1000)
  );
}

export const counterSlice = createSlice({
  // name用于redux devtools查看dispatch
  name: 'counter',
  initialState: {
    value: 0,
    status: 'idle',
  },
  reducers: {
    increment: (state) => {
      // state不需要immutable(return一个新state), 直接改即可(toolkit已集成Immer)
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    // dispatch带参数 dispatch(incrementByAmount(incrementValue))
    incrementByAmount: (state, action) => {
      state.value += action.payload;
    },
  }
});

// 1 导出actions
export const { increment, decrement, incrementByAmount } = counterSlice.actions;

// 2 导出select(已集成reselect)
// 也可以在业务组件中 const { value } = useSelector((state) => state.counter)
// export const selectCount = (state) => state.counter.value;

// 3 导出thunk(已集成redux-thunk)
export const increment100IfOddAsync = () => async (dispatch, getState) => {
  const currentValue = getState().counter.value
  if (currentValue % 2 === 1) {
    // 里面可以放异步请求
    const { data } = await fetchCountApi(100);
    dispatch(incrementByAmount(data));
    // 可以访问其他slice的state和action
    dispatch(incrementAge(getState().person.age))
  }
};

// 4 导出给configureStore
export default counterSlice.reducer;
